package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.CollectionBehaviorConstant;
import com.heima.common.constants.LikesConstants;
import com.heima.common.constants.UnLikesBehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoResult;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApUserFan;
import com.heima.model.behavior.dto.ArticleInfoDto;
import com.heima.model.behavior.dto.CollectionBehaviorDto;
import com.heima.model.behavior.dto.LikesBehaviorDto;
import com.heima.model.behavior.dto.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2022/11/8 9:41
 * @Version 1.0
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Resource
    private ApArticleMapper articleMapper;
    @Resource
    private ApArticleConfigMapper configMapper;
    @Resource
    private ApArticleContentMapper contentMapper;
    @Autowired
    private ArticleDetailService articleDetailService;
    @Autowired
    private CacheService cacheService;

    private final static Integer DEFAULT_SIZE = 10;

    @Override
    public ResponseResult loadArticle(ArticleHomeDto homeDto, Integer type) {
        paramCheck(homeDto);
        return ResponseResult.okResult(articleMapper.loadArticle(homeDto,type));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveArticle(ArticleDto dto) throws Exception{
        if(StringUtils.isEmpty(dto.getContent()) || StringUtils.isEmpty(dto.getTitle())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        apArticle.setPublishTime(new Date());

        if(dto.getId() == null){
            save(apArticle);
            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(apArticle.getId());
            config.setIsForward(true);
            config.setIsDown(false);
            config.setIsDelete(false);
            config.setIsComment(true);
            configMapper.insert(config);

            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            contentMapper.insert(content);
        }else {
            updateById(apArticle);
            ApArticleContent content = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            content.setContent(dto.getContent());
            contentMapper.updateById(content);
        }

        //生成静态资源文件
        articleDetailService.createStaticHtml(dto.getContent(),apArticle.getId());
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 文章详情回显行为数据
     *
     * @param articleInfoDto
     * @param request
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto articleInfoDto, HttpServletRequest request) {
        //1.校验参数
        if (articleInfoDto == null) {
            log.info("加载文章详情行为参数无效");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        //获取用户id
        String userId = request.getHeader("userId");
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.是否关注文章作者
        boolean isFollow = isFollow(articleInfoDto);
        //4.是否收藏文章
        boolean isCollection = isCollection(articleInfoDto,userId);
        //5.是否点赞了文章
        boolean isLike = isLike(articleInfoDto, userId);
        //6.是否喜欢文章
        boolean isUnlike = isUnlike(articleInfoDto, userId);

        //封装结果返回
        ArticleInfoResult articleInfoResult = new ArticleInfoResult();
        articleInfoResult.setIslike(isLike);
        articleInfoResult.setIscollection(isCollection);
        articleInfoResult.setIsunlike(isUnlike);
        articleInfoResult.setIsfollow(isFollow);
        return ResponseResult.okResult(articleInfoResult);
    }

    /**
     * 是否点赞
     * @param articleInfoDto
     * @param userId
     * @return
     */
    private boolean isLike(ArticleInfoDto articleInfoDto, String userId) {
        boolean flag = false;
        String  likesBehaviorDtoJson = (String) cacheService.hGet(LikesConstants.USER_LIKE_BEHAVIOR + "-" + userId, articleInfoDto.getArticleId() + "");
        LikesBehaviorDto behaviorDto = JSON.parseObject(likesBehaviorDtoJson, LikesBehaviorDto.class);
        if (behaviorDto == null) {
            return flag;
        }
        if (UnLikesBehaviorConstants.LIKE.equals(behaviorDto.getOperation())) {
            flag = true;
        }
        return flag;
    }

    /**
     * 是否收藏
     * @param articleInfoDto
     * @param userId
     * @return
     */
    private boolean isCollection(ArticleInfoDto articleInfoDto, String userId) {
        boolean flag = false;
        String jsonCollectionBehaviorDto = (String) cacheService.hGet(CollectionBehaviorConstant.COLLECTION_BEHAVIOR + userId, articleInfoDto.getArticleId() + "");
        //转换为CollectionBehaviorDto
        CollectionBehaviorDto collectionBehaviorDto = JSON.parseObject(jsonCollectionBehaviorDto, CollectionBehaviorDto.class);
        if (collectionBehaviorDto != null) {
            if (CollectionBehaviorConstant.COLLECTION.equals(collectionBehaviorDto.getOperation())) {
                //收藏
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 是否喜欢
     * @param articleInfoDto
     * @param userId
     * @return
     */
    private boolean isUnlike(ArticleInfoDto articleInfoDto, String userId) {
        boolean flag = false;
        String jsonUnlike = (String) cacheService.hGet(UnLikesBehaviorConstants.USER_UNLIKE_BEHAVIOR + userId, articleInfoDto.getArticleId() + "");
        if (!StringUtils.isEmpty(jsonUnlike)) {
            UnLikesBehaviorDto unLikesBehaviorDto = JSON.parseObject(jsonUnlike, UnLikesBehaviorDto.class);
            if (unLikesBehaviorDto.getType().equals(UnLikesBehaviorConstants.LIKE)) {
                flag = true;
            }
        }

        return flag;
    }

    /**
     * 判断是否关注作者
     * @param articleInfoDto
     * @return
     */
    private boolean isFollow(ArticleInfoDto articleInfoDto) {
        boolean flag = false;
        String jsonApUserFan = cacheService.get("AuthorId" + articleInfoDto.getAuthorId().toString());
        List<ApUserFan> apUserFans = JSON.parseArray(jsonApUserFan, ApUserFan.class);
        if (apUserFans != null) {
            for (ApUserFan apUserFan : apUserFans) {
                if (apUserFan.getUserId().equals(articleInfoDto.getAuthorId())) {
                    flag = true;
                }
            }
        }
        return flag;
    }

    private void paramCheck(ArticleHomeDto homeDto){
        //基本判断
        if(homeDto.getMinBehotTime() == null) {
            homeDto.setMinBehotTime(new Date());
        }
        if(homeDto.getMaxBehotTime() == null) {
            homeDto.setMaxBehotTime(new Date());
        }
        if(homeDto.getSize() == null){
            homeDto.setSize(DEFAULT_SIZE);
        }
        if(StringUtils.isEmpty(homeDto.getTag())){
            homeDto.setTag("__all__");
        }
    }
}